package com.aggron.concurrency.examples.atomic;

import com.aggron.concurrency.annotations.ThreadSafe;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author LR2SD
 * @description AtomicBoolean原子并发测试类
 * @date 2018-06-10 09:15
 */
@Slf4j
@ThreadSafe
public class AtomicExample5 {

   private static AtomicBoolean isHappened=new AtomicBoolean(false);
    /**
     * 请求总数
     */
    public static  int clientTotal=5000;
    /**
     * 同时执行线程的总数
     */
    public static  int threadTotal =200;



    public static void main(String [] args) throws Exception {
        //线程池
        ExecutorService executorService= Executors.newCachedThreadPool();
        //信号量--允许的最大并发量
        final Semaphore semaphore=new Semaphore(threadTotal);

        //阻塞当前线程，直至线程减少到0时
        final CountDownLatch countDownLatch=new CountDownLatch(clientTotal);

        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    test();
                    semaphore.release();
                } catch (Exception e) {
                    log.error(e.getMessage(),e);
                }
                countDownLatch.countDown();

            });
        }

        countDownLatch.await();
        executorService.shutdown();
        log.info("isHappened:{}",isHappened.get());
    }

    private static void test(){
        //原子操做
        if(isHappened.compareAndSet(false,true)){
            log.info("execute");
        }
    }
}
